<template>
  <div class="new_dynamic_contant margin">
    <Tabs value="name1">
      <TabPane label="发布动态" name="name1">
        <div>
          <!-- 文本域 -->
          <Input
            v-model="text"
            autosize
            type="textarea"
            placeholder="说点什么吧..."
          ></Input>

          <!-- 图片选择器 -->
          <!-- 显示 -->
          <!-- 循环upload -->
          <div
            style="margin-top: 10px"
            class="demo-upload-list"
            v-for="(item, i) in uploadList"
            :key="i"
          >
            <!-- 完成状态 -->
            <template v-if="item.status === 'finished'">
              <Image :src="item.url" fit="cover" width="100%" height="100%" />
              <!-- <img :src="item.url" alt=""> -->
              <div class="demo-upload-list-cover">
                <!-- 查看大图 -->
                <Icon
                  type="ios-eye-outline"
                  @click="handleView(item.name, item.url)"
                ></Icon>
                <!-- 删除 -->
                <Icon
                  type="ios-trash-outline"
                  @click="handleRemove(item)"
                ></Icon>
              </div>
            </template>
            <!-- 进度条 -->
            <template v-else>
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
              ></Progress>
            </template>
          </div>
          <!-- 添加 -->
          <Upload
            ref="upload"
            :show-upload-list="false"
            :format="['jpg', 'jpeg', 'png']"
            accept="jpg,jpeg,png"
            :max-size="1024 * 10"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            multiple
            type="drag"
            action="//jsonplaceholder.typicode.com/posts/"
            style="display: inline-block; width: 58px; margin-top: 10px"
          >
            <div style="width: 58px; height: 58px; line-height: 58px">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <!-- 查看大图 -->
          <ImagePreview v-model="visible" :preview-list="[imgurl]" />
          <br />

          <Button style="margin-top: 10px" long @click="submit"
            >发布动态</Button
          >
        </div>
      </TabPane>
      <TabPane label="编辑动态" name="name2">
        <div>
          <!-- 操作中 -->
          <Spin fix :show="is_showSpin"></Spin>
          <!-- 对话框 -->
          <Modal v-model="modal1" width="360">
            <template #header>
              <p style="color: #f60; text-align: center">
                <Icon type="ios-information-circle"></Icon>
                <span>确认初始化吗</span>
              </p>
            </template>
            <div style="text-align: center">
              <div>如果是第一次使用请初始动态列表</div>
              <div>如果使用过,该操作会清空动态列表数据</div>
            </div>
            <template #footer>
              <Button type="error" size="large" long @click="modal_clearList"
                >删除</Button
              >
            </template>
          </Modal>
          <!-- 编辑对话框 -->
          <Modal
            style="padding: 50px 40px 40px"
            v-model="edit_modal"
            @on-ok="save_edit_data"
            @on-cancel="edit_modal = false"
          >
            <Input
              style="margin-top: 30px"
              v-model="edit_data.text"
              type="textarea"
              :autosize="true"
              placeholder=""
            />
            <Upload
              :format="['jpg', 'jpeg', 'png']"
              :max-size="1024 * 10"
              :before-upload="edit_data_addimg"
              multiple
              type="drag"
              action="//jsonplaceholder.typicode.com/posts/"
              style="
                display: inline-block;
                width: -webkit-fill-available;
                margin-top: 10px;
              "
            >
              <div>
                <Icon type="ios-camera" size="20"></Icon>
              </div>
            </Upload>
            <Space wrap style="margin-top: 10px">
              <template v-for="(url, index) in edit_data.img" :key="index">
                <Image
                  :src="url"
                  fit="contain"
                  width="120px"
                  height="80px"
                  preview
                  :preview-list="edit_data.img"
                  :initial-index="index"
                />
                <a style="display: block" @click="edit_data_delimg(url)"
                  >删除</a
                >
              </template>
            </Space>
          </Modal>
          <!-- 下拉菜单 -->
          <div style="text-align: center">
            <Dropdown @on-click="dealclik" trigger="click">
              <a href="javascript:void(0)">
                高级操作
                <Icon type="ios-arrow-down"></Icon>
              </a>
              <template #list>
                <DropdownMenu>
                  <DropdownItem name="clearList">初始化动态列表</DropdownItem>
                </DropdownMenu>
              </template>
            </Dropdown>
          </div>
          <!-- 动态列表 -->
          <Scroll
            class="centent"
            :on-reach-bottom="handleReachBottom"
            :distance-to-edge="distance"
            :height='clientHeight'
          >
            <Card
              v-for="(item, index) in showlist"
              :key="index"
              style="margin: 10px"
            >
              <Input
                :border="false"
                autosize
                readonly
                v-model="item.text"
                type="textarea"
                placeholder=""
              />

              <Space wrap>
                <template v-for="(base64, index) in item.img" :key="index">
                  <Image
                    :src="base64"
                    fit="contain"
                    width="120px"
                    height="80px"
                    preview
                    :preview-list="item.img"
                    :initial-index="index"
                  />
                </template>
              </Space>
              <br />
              <br />
              <div>
                <Icon type="ios-time-outline" />发布时间:
                {{ item.time }}
                &emsp; &emsp;
                <Icon
                  type="ios-create-outline"
                  title="编辑"
                  @click="edit_dynamic(item)"
                />
                &emsp;
                <Icon
                  type="ios-trash"
                  title="删除"
                  @click="del_dynamic(item, true)"
                />
              </div>
            </Card>
          </Scroll>
        </div>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
import { getObjectURL, filetoBase64, getUuid, decode } from '@/mylibs/functions'
import { PATH_Dynamic_file, PATH_Dynamic_list } from '@/mylibs/define'
import putBuffer from '@/api/API_Uploading_Directory_Tree'

export default {
  data() {
    return {
      // defaultList: [
      //   {
      //     name: 'image-demo-1.jpg',
      //     url: 'https://file.iviewui.com/images/image-demo-1.jpg'
      //   },
      // ],
      is_showSpin: false,
      modal1: false,
      imgName: '',
      visible: false,
      uploadList: [],
      // 文本域
      text: '',
      imgurl: '',
      imgBase64List: [],
      showlist: [],
      dynamicList: [],
      index_page: 0,
      page_show_num: 5,
      distance: [-1, -1],
      edit_data: { text: '', img: [] },
      edit_modal: false,
      clientHeight: 400
    }
  },
  mounted() {
    this.clientHeight = document.body.clientHeight
    window.onresize = () => {
      //屏幕尺寸变化就重新赋值
      return (() => {
        this.clientHeight = document.body.clientHeight
      })()
    }
  },
  methods: {
    // 查看大图
    handleView(name, url) {
      this.imgurl = url
      this.imgName = name
      this.visible = true
    },
    // 删除文件
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList
      this.uploadList.splice(fileList.indexOf(file), 1)
      this.imgBase64List.splice(fileList.indexOf(file), 1)
    },
    // 格式错误
    handleFormatError(file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc:
          'File format of ' +
          file.name +
          ' is incorrect, please select jpg or png.'
      })
    },
    // 超出大小
    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超过文件大小限制',
        desc: 'File  ' + file.name + '太大了,不超过10M'
      })
    },
    handleBeforeUpload(file) {
      // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者 Promise 则停止上传
      const check = this.uploadList.length < 10
      if (!check) {
        this.$Notice.warning({
          title: '最多可上传10张图片。'
        })
        return false
      }
      // <template v-if="item.status === 'finished'">
      // 添加status 属性,让上面显示图片
      file['status'] = 'finished'
      // base64
      filetoBase64(file, (base64) => {
        this.imgBase64List.push(base64)
        this.$Notice.info({ desc: '图片转base64完成' })
      })
      // 预览
      var url = getObjectURL(file)
      file['url'] = url

      this.uploadList.push(file)
      // 自己上传
      return false
    },
    // 提交数据
    async submit() {
      // 判断
      if (this.text == '') {
        this.$Notice.info('请输入内容...')
        return
      }
      // 这次动态的数据
      var path = PATH_Dynamic_file + getUuid()
      var dynamic = {
        path,
        time: this.$Date().format('YYYY-MM-DD HH:mm:ss'),
        img: this.imgBase64List,
        text: this.text
      }

      var api_ret = null

      // 获取列表,添加路径
      api_ret = await putBuffer('get', PATH_Dynamic_list)
      if (api_ret.ok) {
        if (Array.isArray(api_ret.res)) {
          var list = api_ret.res
          // 提交数据到阿里云oss

          // 新动态添加到开始
          list.unshift(path)
          api_ret = await putBuffer('put', path, dynamic, false)
          // 如果提交成功再保存到目录树
          if (api_ret.ok) {
            this.$Notice.success({ desc: '动态数据保存成功' })

            // 保存
            api_ret = await putBuffer('put', PATH_Dynamic_list, list, false)
            if (!api_ret.ok) {
              this.$Notice.error({
                desc: '动态路径保存到动态列表失败:' + api_ret.err
              })
              this.$Notice.error({ desc: '动态列表保存失败:' + api_ret.err })
            } else {
              // 更新列表
              this.getDynamicList(this.getDynamicData)
              this.$Notice.success({ desc: '动态列表保存成功' })
            }
          } else {
            this.$Notice.error({ desc: '动态保存失败:' + api_ret.err })
          }
        } else {
          this.$Notice.error({ desc: '获取的动态列表非列表类型' })
        }
      } else {
        this.$Notice.error({
          desc: '获取动态列表失败,如果是第一次使用请初始动态列表:' + api_ret.err
        })
      }
    },

    dealclik(name) {
      if (name == 'clearList') {
        this.modal1 = true
      }
    },
    // 初始化动态列表
    async modal_clearList() {
      this.modal1 = false
      this.is_showSpin = true
      var { ok, res, err } = await putBuffer(
        'put',
        PATH_Dynamic_list,
        [],
        false
      )
      if (ok) {
        this.$Notice.success({ desc: '初始化列表成功' })
        // 删除数据
        var { res, ok, err } = await putBuffer('deldir', PATH_Dynamic_file)
        if (ok) {
          this.$Notice.success({ desc: '删除动态数据成功' })
        } else {
          this.$Notice.error({ desc: '删除动态数据失败:' + err })
        }
        PATH_Dynamic_file
      } else {
        this.$Notice.error({ desc: '初始化列表失败:' + err })
      }
      this.is_showSpin = false
    },
    // 上拉加载更多
    handleReachBottom() {
      return new Promise((resolve) => {
        this.getDynamicData()
        resolve()
      })
    },
    // 获取动态列表
    async getDynamicList(fun_back) {
      var { res, ok, err } = await putBuffer('get', PATH_Dynamic_list)
      if (ok) {
        if (Array.isArray(res)) {
          this.dynamicList = res
          if (fun_back) {
            fun_back(0)
          }
        } else {
          this.$Notice.error({ desc: '数据非数组' })
        }
      } else {
        this.$Notice.error({ desc: '获取数据失败:' + err })
      }
    },

    //动态数据
    async getDynamicData(start) {
      if (start) {
        this.index_page = start
      }
      var start = this.index_page * this.page_show_num
      var end = start + this.page_show_num

      if (start >= this.dynamicList.length) {
        this.$Notice.info({ desc: '没有更多数据了哟~' })
        return
      }

      if (end < this.dynamicList.length) {
        var list = this.dynamicList.slice(start, end)

        for (let index = 0; index < list.length; index++) {
          const element = list[index]

          var { res, ok, err } = await putBuffer('get', element)
          if (ok) {
            this.showlist.push(res)
          } else {
            this.$Notice.error({ desc: '获取动态数据失败:' + err })
          }
        }
      } else {
        for (let index = start; index < this.dynamicList.length; index++) {
          const element = this.dynamicList[index]

          var { res, ok, err } = await putBuffer('get', element)
          if (ok) {
            this.showlist.push(res)
          } else {
            this.$Notice.error({ desc: '获取动态数据失败:' + err })
          }
        }
      }

      this.index_page++
    },

    // 编辑动态
    edit_dynamic(data) {
      this.edit_data = data
      this.edit_modal = true
    },

    edit_data_delimg(url) {
      this.edit_data.img.splice(this.edit_data.img.indexOf(url), 1)
    },

    edit_data_addimg(file) {
      filetoBase64(file, (base64) => {
        this.edit_data.img.push(base64)
      })
      return false
    },
    async save_edit_data() {
      this.edit_modal = false

      var { ok, err } = await putBuffer(
        'put',
        this.edit_data.path,
        this.edit_data
      )
      if (ok) {
        this.$Notice.success({ desc: '编辑成功' })
        this.edit_data = { text: '', img: [] }
      } else {
        this.$Notice.success({ desc: '失败成功:' + err })
      }
    },
    // 删除动态
    async del_dynamic(data, is_modal) {
      if (is_modal) {
        this.$Modal.confirm({
          title: '确认删除该动态吗?',
          content: '',
          onOk: () => {
            this.del_dynamic(data, false)
          },
          onCancel: () => {}
        })
      } else {
        var { ok, err } = await putBuffer('del', data.path)
        if (ok) {
          var { ok, res, err } = await putBuffer('get', PATH_Dynamic_list)
          if (ok) {
            if (Array.isArray(res)) {
              res.splice(res.indexOf(data.path), 1)
              var { ok, err } = await putBuffer('put', PATH_Dynamic_list, res)
              if (ok) {
                this.$Notice.success({ desc: '删除成功' })
                this.getDynamicList(this.getDynamicData)
              } else {
                this.$Notice.error({ desc: err })
              }
            }
          }
        } else {
          this.$Notice.error({ desc: '从oss删除失败:' + err })
        }
      }
    }
  },
  created() {
    this.getDynamicList(this.getDynamicData)
  }
}
</script>
<style scoped>

.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.demo-spin-container {
  display: inline-block;

  width: 100%;
  height: 100%;
  position: relative;
  border: 1px solid #eee;
}
.margin {
  margin: 10px 10px;
}

.padding {
  padding: 10px 10px;
}
</style>
